import axios from 'axios'
import { MessageBox, Message, Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['Authorization'] = getToken() || ''

    // Handles array arguments in GET requests
    if (config.method === 'get') {
      config.paramsSerializer = function(params) {
        return qs.stringify(params, { indices: false })
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      // 1005: Illegal token; 1006: Other clients logged in; 1007: Token expired;
      if (res.code === 1005 || res.code === 1006 || res.code === 1007) {
        // to re-login
        MessageBox.confirm(
          'You have been logged out, you can cancel to stay on this page, or log in again',
          'Confirm logout',
          {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        return
      }
      if (res.code.toString().startsWith('1')) {
        Message({
          message: res.message || 'Fail',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        Notification.error({
          title: 'Fail, Please try again',
          message: res.code + '\n' + res.message,
          position: 'bottom-right'
        })
      }
      return Promise.reject('Fail')
    } else {
      return res
    }
  },
  error => {
    console.log('err7:' + error) // for debug
    Notification.error({
      title: 'Fail Request, Please try again',
      message: error.message,
      position: 'bottom-right',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
